package com.miyu.system.utils.crawler.book;



import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.miyu.plugins.utils.Comutils;
import com.miyu.plugins.utils.GetBeanUtil;
import com.miyu.system.dao.system.SystemDao;
import com.miyu.system.pojo.book.BookMain;
import com.miyu.system.pojo.crawler.BookPageVo;
import com.miyu.system.utils.crawler.CrawlerUtils;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.redis.cache.MicaRedisCache;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;

@Slf4j
public class BookSaveThread implements Callable <JSONObject> {
    static MicaRedisCache redisCache = GetBeanUtil.getBeanByClass(MicaRedisCache.class);
    static SystemDao dao = (SystemDao) GetBeanUtil.getBeanByClass(SystemDao.class);
    private final JSONObject data;
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public JSONObject  call() throws Exception {
        int  num =0;//初始话 超过10 不再执行 10*10 100秒没有新数据进入不再处理数据
        System.out.println(data);
        save(num);
        return null;
    }
    private static void save(int num) throws InterruptedException {
        //得到key值
//        long i=1;
        Set<String> scan = redisCache.scan(CrawlerUtils.REDIS_CACHE_BOOK_COLLECT+"*");
        log.info("取值长度："+scan.size());
        if(!scan.isEmpty()){
            num =0;//重置等待时长
            for (String key : scan) {
                BookPageVo vp =  redisCache.get(key);
                //解析保存数据
                if (vp != null) {
                    try {
                        bookSaveJx(vp);
                        redisCache.del(key);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        throw new RuntimeException(e);
                    }

                }
            }
            //移除所有key
//            redisCache.del(scan);
            //再次进入递归
            save(num);
        }else {
            Thread.sleep(10000);
            log.info("等待时间："+num+"秒");
            num++;
            if(num<10)
                save(num);//递归线程

        }
    }

    private static void bookSaveJx(BookPageVo pv) {
        String[] table = CrawlerUtils.BOOK_CHAPTER;
        Random rd=new Random();
        String ta = pv.getRuleId()+"_"+table[rd.nextInt(table.length)];
        /** 主表*/
        String mainTable = "book_main_"+pv.getRuleId();
        /** 章节表*/
        String chapterTable = "book_chapter_"+ta;

        List<String> sqlList = new ArrayList<String>();
        JSONArray jsonArray = pv.getData().getJSONArray(BookOperate.BOOK_DETAIL.getCode());
        if(jsonArray==null||jsonArray.isEmpty()){
            return ;
        }
        JSONObject bookDetail = jsonArray.getJSONObject(0);
        JSONArray bookChapter =  pv.getData().getJSONArray(BookOperate.BOOK_CHAPTER.getCode());
        /** 数据转换*/
        BookMain bookMain = JSONObject.parseObject(bookDetail.toJSONString(), BookMain.class);

        bookMain.setRuleId(pv.getRuleId());///规则主键
        bookMain.setType("0");//类型0 text 1 其他
        bookMain.setBookId(Comutils.getId(CrawlerUtils.TABLE_BOOK_MAIN));//书Id
        StringBuffer main = new StringBuffer();
        main.append("insert into ").append(mainTable).append("(book_id,rule_id,book_url,toc_url,origin,name,author,kind,cover_url,intro,type,latest_chapter_title,");
        main.append(" latest_chapter_time,last_check_count,total_chapter_num)");
        main.append("values(");
        main.append("'").append(isNullToStr(bookMain.getBookId()) ).append("',");
        main.append("'").append(isNullToStr(bookMain.getRuleId())).append("',");
        main.append("'").append(isNullToStr(bookMain.getBookUrl())).append("',");
        main.append("'").append(isNullToStr(bookMain.getTocUrl())).append("',");
        main.append("'").append(chapterTable).append("',");
        main.append("'").append(isNullToStr(bookMain.getName())).append("',");
        main.append("'").append(isNullToStr(bookMain.getAuthor())).append("',");
        main.append("'").append(isNullToStr(bookMain.getKind())).append("',");
        main.append("'").append(isNullToStr(bookMain.getCoverUrl())).append("',");
        main.append("'").append(isNullToStr(bookMain.getIntro())).append("',");
        main.append("'").append(isNullToStr(bookMain.getType())).append("',");
        main.append("'").append(isNullToStr(bookMain.getLatestChapterTitle())).append("',");
        main.append("'").append(isNullToStr(bookMain.getLastCheckTime())).append("',");
        main.append("'").append(isNullToStr(bookMain.getLastCheckCount())).append("',");
        main.append("'").append(isNullToStr(bookMain.getTotalChapterNum())).append("')");
        sqlList.add(main.toString());
        if(!(bookChapter==null||bookChapter.isEmpty())){
            for (int i = 0; i < bookChapter.size(); i++) {
                JSONObject chapter = bookChapter.getJSONObject(i);
                StringBuffer sb = new StringBuffer();
                sb.append("insert into ").append("");
                sb.append(chapterTable);
                sb.append("(chapter_id,book_id,url,title,num)");
                sb.append("values(");
                sb.append("'").append(Comutils.getId(CrawlerUtils.TABLE_BOOK_CHAPTER)).append("',");
                sb.append("'").append(isNullToStr(bookMain.getBookId())).append("',");
                sb.append("'").append(isNullToStr(chapter.getString("url"))).append("',");
                sb.append("'").append(isNullToStr(chapter.getString("title"))).append("',");
                sb.append("'").append(isNullToStr(chapter.getString("num"))).append("')");
                sqlList.add(sb.toString());
            }
        }
        try {
            dao.doExecuteBatch(sqlList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

    }

    private static String isNullToStr(Object obj) {
        String str="";
        if("null".equals(obj)||null==obj|| StrUtil.isEmpty(String.valueOf(obj))){
            str="";
        }else{
            return String.valueOf(obj);
        }
        return str;
    }

    /**
     * 书籍保存线程
     */
    public BookSaveThread(JSONObject data){
        this.data = data;
    }
}
